/**
 * program create index file
 * Date:2008-11-20
 * Author:Wang Lijun
 * Email:unix_jun@yahoo.com.cn
 *
 */

#include <iostream>
#include <string>

#include <tr1/memory>

#include <unistd.h>
#include <getopt.h>

#include "vector_space_indexer.h"
#include "page_db.h"
#include "junix.h"

//using namespace jsearch;

std::string program_name;

struct option long_options[]=
{
	{"db",required_argument,NULL,'d'},
	{"index_dir",required_argument,NULL,'i'},
	{"page_db",required_argument,NULL,'p'},
	{"version",no_argument,NULL,'v'},
	{"help",no_argument,NULL,'h'}
};

void usage(int status)
{
	if (status)	{
		std::cerr<<"Try "<<program_name
			<<" --help for more infomation"
			<<std::endl;
	} else {
		std::cout<<"Usage:"
			<<program_name
			<<" [OPTIONS]"<<std::endl<<std::endl
			<<"--db        -d   Where the indexed data to store"<<std::endl
			<<"--index_dir -i   Dir in which all ASCII files will be indexed"
			<<std::endl
			<<"--page_db   -p   File to store page_db"<<std::endl
			<<"--version   -v   Show version"<<std::endl
			<<"--help      -h   Show help infomation"<<std::endl
			<<std::endl
			<<"Bug Report<unix_jun@yahoo.com.cn>"<<std::endl;
	}
}

void show_version()
{
	std::cout<<"simple indexer 0.01"<<std::endl
		<<"Author: Wang Li Jun"<<std::endl;
}

int main(int argc, char **argv)
{
	program_name = argv[0];
	std::string disk_db="rindex.db";
	std::string scan_dir="./";
	std::string page_db_file="PAGE.db";

	char *cp;
	if ( (cp=getcwd(NULL,0)) != NULL) {
		scan_dir=std::string(cp);
		free(cp);
	}

	char c;
	while( (c=getopt_long(argc, argv,"d:i:p:vh",long_options,0)) != EOF)
	{
		switch (c) {
			case 'd':
				disk_db = std::string(optarg);
				break;
			case 'i':
				scan_dir = std::string(optarg);
				break;
			case 'p':
				page_db_file = std::string(optarg);
				break;
			case 'v':
				show_version();
				exit(0);
			case 'h':
				usage(0);
				exit(0);
			default:
				usage(1);
				exit(1);
				break;
		}
	}


	typedef std::tr1::shared_ptr<jsearch::page_db> SPDB;
	SPDB pdb(new jsearch::page_db(scan_dir,page_db_file)); 

	pdb->create_db();

	jsearch::vector_space_indexer indexer(pdb,disk_db);

	indexer.build_index();
	indexer.persist();

	return 0;
}
